package android.framework.reflaction.injectors;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.framework.reflaction.annotation.OnClickListenerInjectionAnnotation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class OnClickListenerInjector implements IReflactionInjector{

	public void Inject(View view, final Object obj) {
		Class<?> cls = obj.getClass();
		Method[] declaredMethods = cls.getDeclaredMethods();
		for (final Method method : declaredMethods) {
			OnClickListenerInjectionAnnotation clickListenerInjection = method.getAnnotation(OnClickListenerInjectionAnnotation.class);
			if(clickListenerInjection != null){
				Class<?>[] parameterTypes = method.getParameterTypes();
				boolean thereIsMoreThanOneParameter = parameterTypes.length > 1;
				boolean TheParameterIsNotView = parameterTypes.length == 1 && parameterTypes[0] != View.class;
				if(thereIsMoreThanOneParameter || TheParameterIsNotView){
					Log.w(this.getClass().getSimpleName(), "can't inject to method because his signature(it's should get non parameters or just one View type): " + method.getName());
				}
				int value = clickListenerInjection.value();
				View v = view.findViewById(value);
				final Object[] args;
				if(parameterTypes.length == 1){
					args = new Object[1];
					args[0] = v;
				}
				else{
					args = new Object[0];
				}
				v.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						try {
							method.setAccessible(true);
							method.invoke(obj, args);
						} catch (IllegalArgumentException e) {
							Log.e(getClass().getSimpleName(), "can't invoke method " + method.getName(), e);
						} catch (IllegalAccessException e) {
							Log.e(getClass().getSimpleName(), "can't invoke method " + method.getName(), e);
						} catch (InvocationTargetException e) {
							Log.e(getClass().getSimpleName(), "can't invoke method " + method.getName(), e);
						}
						
					}
				});
			}
		}
	}

}
